package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.Convert;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        //根据文件路径，找到bpmn文件
        //path:/upload/2021/11/17/40c5252f-80aa-4fc2-8757-329bc07829d9.bpmn
        //SystemConfig.getProfile():D:/upload/upload
        BpmnInfo bpmnInfo = new BpmnInfo();
        File bpmnFile = new File(SystemConfig.getProfile(), path);
        //将流程文件部署到Activiti7中
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(path, new FileInputStream(bpmnFile))
                .deploy();
        bpmnInfo.setBpmnType(bpmnType);//什么类型的审核
        bpmnInfo.setDeployTime(new Date());//部署时间
        bpmnInfo.setDeploymentId(deploy.getId());//部署的ID
        bpmnInfo.setInfo(info);//备注信息
        //根据Activiti生成部署对象，查出流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        //封装成bpmnInfo对象，保存到数据库中
        bpmnInfo.setBpmnName(processDefinition.getName());//流程定义名称
        bpmnInfo.setActProcessId(processDefinition.getId());//流程定义ID
        bpmnInfo.setActProcessKey(processDefinition.getKey());//流程定义key
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        //根据部署ID,查询流程定义对象，
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if ("xml".equalsIgnoreCase(type)){
            //通过流程定义对象获取resourceName
            String resourceName = processDefinition.getResourceName();
            return repositoryService.getResourceAsStream(deploymentId,resourceName);
        }else {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            return generator.generateDiagram(bpmnModel,
                    Collections.EMPTY_LIST,Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
        }
    }

    @Override
    public void delete(Long id) {
        //根据id查询bpmn对象
        BpmnInfo bpmnInfo = this.get(id);
        //删除bpmninfo对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //查询目前这个流程定义正在进行的流程实例
        //找流程实例相关的BusinessKey的业务对象

        //获取流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //删除activiti中的流程定义对象
        repositoryService.deleteDeployment(processDefinition.getDeploymentId(),true);
    }

    @Override
    public BpmnInfo queryByType(String bus_car_package) {
        return bpmnInfoMapper.queryByType(bus_car_package);
    }
}
